package com.mingqi.enetconnected.primary;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.base.ActivityManager;
import com.mingqi.enetconnected.base.BaseFragment;
import com.mingqi.enetconnected.base.MyApplication;
import com.mingqi.enetconnected.daemon.DaemonHolder;
import com.mingqi.enetconnected.location.service.LocationService;
import com.mingqi.enetconnected.primary.mytask.MyTaskFragment;
import com.mingqi.enetconnected.primary.personcentre.PersonCentreFragment;
import com.mingqi.enetconnected.primary.worktable.WorkTableFragment;
import com.mingqi.enetconnected.service.BackgroundService;
import com.mingqi.enetconnected.util.helper.BackHandlerHelper;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.rg_bottom)
    RadioGroup mRgBottom;
    private ArrayList<BaseFragment> mBaseFragment;
    /**
     * 选中的Fragment的对应的位置
     */
    private int mPosition;
    /**
     * 上次切换的Fragment
     */
    private Fragment mPreContent;

    private LocationService locationService;
    private ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_app);
        ButterKnife.bind(this);

        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();

        mImmersionBar.fitsSystemWindows(false).transparentStatusBar().init();

        initFragment();
        //设置RadioGroup的监听
        setListener();

        ActivityManager.getInstance().addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
    }

    @Override
    protected void onStart() {
        super.onStart();
//        startBackgroundService();
//        startRequestLocation();

    }

    private void setListener() {

        mRgBottom.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        //设置默认选中首页
        ((RadioButton) mRgBottom.getChildAt(1)).setChecked(true);
    }

    private void initFragment() {

        mBaseFragment = new ArrayList<>();
        //我的任务Fragment
        mBaseFragment.add(new MyTaskFragment());
        //工作台Fragment
        mBaseFragment.add(new WorkTableFragment());
        //个人中心Fragment
        mBaseFragment.add(new PersonCentreFragment());
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {

                //我的任务
                case R.id.rb_my_task:
                    mPosition = 0;
                    break;

                //工作台
                case R.id.rb_work_table:
                    mPosition = 1;
                    break;

                //个人中心
                case R.id.rb_person_centre:
                    mPosition = 2;
                    break;

                default:
                    mPosition = 0;
                    break;
            }

            //根据位置得到对应的Fragment
            BaseFragment toFragment = getFragment();
            //替换
            switchFragment(mPreContent, toFragment);
        }
    }

    /**
     * 根据位置得到对应的Fragment
     *
     * @return
     */
    private BaseFragment getFragment() {

        BaseFragment fragment = mBaseFragment.get(mPosition);
        return fragment;
    }

    /**
     * @param fromFragment 刚显示的Fragment,马上就要被隐藏了
     * @param toFragment   马上要切换到的Fragment，一会要显示
     */
    private void switchFragment(Fragment fromFragment, Fragment toFragment) {

        if (fromFragment != toFragment) {

            mPreContent = toFragment;
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            //才切换
            //判断有没有被添加
            if (!toFragment.isAdded()) {
                //to没有被添加
                //from隐藏
                if (fromFragment != null) {
                    ft.hide(fromFragment);
                }
                //添加to
                if (toFragment != null) {
                    ft.add(R.id.fl_content, toFragment).commit();
                }
            } else {
                //to已经被添加
                // from隐藏
                if (fromFragment != null) {
                    ft.hide(fromFragment);
                }
                //显示to
                if (toFragment != null) {
                    ft.show(toFragment).commit();
                }
            }
        }
    }

    /**
     * 定义一个变量，来标识是否退出
     */
    private static boolean isExit = false;
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //2秒后恢复原状态
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//
//            exit();
//            return true;
//        }

        return super.onKeyDown(keyCode, event);
    }

    private void exit() {

        if (!isExit) {
            isExit = true;

            Toast.makeText(MainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();

            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            stopRequestLocation();
            finish();
            System.exit(0);
        }
    }

    @Override
    public void onBackPressed() {

        if (getFragment() != null) {

            boolean isHandle = BackHandlerHelper.handleBackPress(this);
            if (!isHandle) {

                moveTaskToBack(true);
            }

        } else {
            super.onBackPressed();
        }
    }

    /**
     * 打开百度定位
     */
    private void startRequestLocation(){
        locationService = ((MyApplication) getApplication()).locationService;
        locationService.registerListener();
        locationService.start();
    }

    /**
     * 关闭百度定位
     */
    private void stopRequestLocation(){
        locationService.unregisterListener(); //注销掉监听
        locationService.stop();
    }

    private void startBackgroundService(){
        DaemonHolder.init(MyApplication.sContext, BackgroundService.class);
     //   startService(new Intent(this, BackgroundService.class));
    }
}
